package cn.edu.sspu.www.controller.user;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.sspu.www.contant.Constants;
import cn.edu.sspu.www.domain.SysUser;
import cn.edu.sspu.www.service.SysUserService;

@Controller
@RequestMapping("/unauth")
public class LoginController {
	
	@Autowired
	private SysUserService service;
	
	/**
	 * 登录
	 * @param queryVo
	 * @return   method = RequestMethod.GET
	 */
	@RequestMapping(value = "/login")
	public ModelAndView login(HttpServletRequest request) {

		ModelAndView view = new ModelAndView();
		if (valideSession(request.getSession())) { // 跳转欢迎界面
			view.setViewName("redirect:/welcome.action");
		} else {
			view.addObject("msg", "登录");
			view.setViewName("user/login");
		}
		return view;
	}

	/**
	 * 登录
	 * @param queryVo
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login(HttpServletRequest request, SysUser queryVo) {

		ModelAndView view = new ModelAndView();
		
		List<SysUser> list = service.querySysUserList(queryVo);
		
		if (list.size() == 1) {
			SysUser sysUser = list.get(0);
			request.getSession().setAttribute(Constants.SESSION_KEY, sysUser);
			view.setViewName("redirect:/welcome.action");
		} else {
			view.addObject("queryVo", queryVo);
			view.addObject("msg", "账号密码错误，请重新登录");
			view.setViewName("user/login");
		}	
		
		return view;
	}
	
	/**
	 * 注册
	 * @param sysUser
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public ModelAndView register(HttpServletRequest request) {
		
		ModelAndView view = new ModelAndView();
		if (valideSession(request.getSession())) { // 跳转欢迎界面
			view.setViewName("redirect:/welcome.action");
		} else {
			view.addObject("msg", "注册");
			view.setViewName("user/register");
		}
		return view;
	}
	
	/**
	 * 注册
	 * @param sysUser
	 * @return
	 */
	@RequestMapping("/register")
	public ModelAndView register(HttpServletRequest request, SysUser sysUser) {
		
		int count = service.addSysUser(sysUser);
		
		ModelAndView view = new ModelAndView();
		if (count == 1) {
			request.getSession().removeAttribute(Constants.SESSION_KEY);
			view.addObject("msg", "【" + sysUser.getNickName() + "】注册成功");
			view.setViewName("user/login");
		} else {
			view.addObject("sysUser", sysUser);
			view.addObject("msg", "注册失败，请重新注册");
			view.setViewName("user/register");
		}
		return view;
	}
	
	/**
	 * session验证
	 * @param session
	 * @return 
	 */
	private boolean valideSession(HttpSession session) {
		if(null != session.getAttribute(Constants.SESSION_KEY)) {
			return true;
		}
		return false;
	}

}
